package com.my.blog.website.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Enumeration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 重命名图片
 * Created by BlueT on 2017/3/22.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ReName {
	
	/**
	 * 	读取resources目录下的资源文件
	 * 	实现思路：
	 *		获取到资源目录resources下的a.txt文件流(假设)，由于产生的InputStream只能读取一次(为什么？)，所以使用BufferedReader读取一行
	 *	1.读取resources路径下的资源文件加载为InputStream
	 *	2.转换成BufferedReader
	 *	3.每次读取一行，读完为止
	 *	4.关闭IS
	 *	5.关闭readered
	 *		
	 * @throws IOException
	 */
	@Test
	public void readResources() throws IOException{
		
		StringBuilder sb = new StringBuilder();
		InputStream is = this.getClass().getResourceAsStream("/static/user/img/rand2/1.txt");
		BufferedReader reader = null;
		
		reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		String line = "";
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\n");
		}
		
		is.close();
		reader.close();
		
		System.out.println(sb);
		System.out.println("执行完毕。");
	}
	
	
	/**
	 * 	读取resources目录下的 /static/user/img/rand2 的所有文件，并全部重命名
	 * 	实现思路：
	 * 		1.使用File读取到项目根目录
	 * 		2.读取目录下的所有文件
	 * 		3.全部重命名
	 * 	
	 * @throws IOException
	 */
	@Test
	public void readResourcesAllFile() throws IOException {
		
		File directory = new File("");
		StringBuilder path = new StringBuilder(directory.getCanonicalPath());
		String imgPath = "\\src\\main\\resources\\static\\user\\img\\rand2\\";
		path.append(imgPath);
		
		File file = new File(path.toString());
		File[] fileList = file.listFiles();
		int i = 0;
		for (File tmp : fileList) {
			tmp.renameTo(new File(path.toString() + (i++) + ".jpg"));
		}
		
		System.out.println("重命名完毕。");
	}
	
	
	
	public static void main(String[] args) throws IOException {
		
		File directory = new File("");
		StringBuilder path = new StringBuilder(directory.getCanonicalPath());
		String imgPath = "\\src\\main\\resources\\static\\user\\img\\avatar\\";
		path.append(imgPath);
		
		File file = new File(path.toString());
		File[] fileList = file.listFiles();
		int i = -1;
		for (File tmp : fileList) {
			tmp.renameTo(new File(path.toString() + i + ".jpg"));
			System.out.println(i);
			i++;
		}
		
		System.out.println("重命名完毕。");
	}
	
	
}
